package com.chinafree.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinafree.auth.model.enumeration.Column;
import com.chinafree.business.model.param.DeliveryParam;
import com.chinafree.business.model.queryCondition.DeliveryQueryCondition;
import com.chinafree.business.model.result.DeliveryResult;
import com.chinafree.business.model.result.UserBaseMessageResult;
import com.chinafree.business.service.DeliveryService;
import com.chinafree.common.model.enumeration.ResponseCodeEnum;
import com.chinafree.common.model.response.BaseResponse;
import com.chinafree.common.model.response.ListPagingResponse;
import com.chinafree.mapper.MaCompanyMapper;
import com.chinafree.mapper.MaJobMapper;
import com.chinafree.mapper.MaUserDeliveryMapper;
import com.chinafree.model.po.MaCompany;
import com.chinafree.model.po.MaJob;
import com.chinafree.model.po.MaUserDelivery;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import com.chinafree.business.service.ResumeService;

@Service
public class DeliveryServiceImpl extends BaseServiceImpl implements DeliveryService {

    @Autowired
    private MaUserDeliveryMapper maUserDeliveryMapper;

    @Autowired
    private MaJobMapper maJobMapper;

    @Autowired
    private MaCompanyMapper maCompanyMapper;

    @Autowired
    public ResumeService resumeService;

    @Override
    @Transactional
    public ListPagingResponse<DeliveryResult> queryUserPage(DeliveryQueryCondition condition) {
        Page<MaUserDelivery> page = new Page<>(condition.getPageIndex(), condition.getPageSize());
        MaUserDelivery maUserDelivery = new MaUserDelivery();
        BeanUtils.copyProperties(condition, maUserDelivery);
        QueryWrapper<MaUserDelivery> entityWrapper = new QueryWrapper<>(maUserDelivery);
        entityWrapper.orderByDesc(Column.CREATE_TIME.getColumn());
        Page<MaUserDelivery> maUserDeliveryPage = maUserDeliveryMapper.selectPage(page, entityWrapper);
        List<MaUserDelivery> records = maUserDeliveryPage.getRecords();
        if (records == null || records.size() == 0) {
            return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", new ArrayList(), 0L, 0, 0L);
        }
        return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", getDeliveryResults(records),
                maUserDeliveryPage.getCurrent(), maUserDeliveryPage.getRecords().size(), maUserDeliveryPage.getTotal());
    }

    @Override
    public BaseResponse insert(DeliveryParam deliveryParam) {
        MaJob majob = maJobMapper.selectById(deliveryParam.getJobId());

        if (majob == null) {
            return new BaseResponse(ResponseCodeEnum.FORBIDDEN, "职位不存在");
        }
        MaUserDelivery build = MaUserDelivery.builder().userId(getUserId()).jobId(deliveryParam.getJobId())
                .companyId(majob.getCompanyId()).build();
        try {
            maUserDeliveryMapper.insert(build);
        } catch (DuplicateKeyException e) {
            return new BaseResponse(ResponseCodeEnum.SUCCESS, "已存在");

        }
        return new BaseResponse(ResponseCodeEnum.SUCCESS, "插入成功");
    }

    @Override
    public BaseResponse update(DeliveryParam deliveryParam, Long user) {
        MaUserDelivery build = new MaUserDelivery();
        BeanUtils.copyProperties(deliveryParam, build);
        // 根据userId和jobId
        UpdateWrapper<MaUserDelivery> userDeliveryUpdateWrapper = new UpdateWrapper<>();
        userDeliveryUpdateWrapper.eq(Column.USER_ID.getColumn(), user);
        userDeliveryUpdateWrapper.eq(Column.JOB_ID.getColumn(), deliveryParam.getJobId());
        maUserDeliveryMapper.update(build, userDeliveryUpdateWrapper);
        return new BaseResponse(ResponseCodeEnum.SUCCESS, "插入成功");
    }

    private List<DeliveryResult> getDeliveryResults(List<MaUserDelivery> records) {
        if (CollectionUtils.isEmpty(records)) {
            return null;
        }
        List<DeliveryResult> deliveryResultList = new ArrayList<>();
        for (MaUserDelivery maUserDelivery : records) {
            Long jobId = maUserDelivery.getJobId();
            MaJob maJob = maJobMapper.selectById(jobId);
            if (maJob == null) {
                continue;
            }
            Long companyId = maJob.getCompanyId();
            if (companyId == null) {
                continue;
            }
            MaCompany maCompany = maCompanyMapper.selectById(companyId);
            if (maCompany == null) {
                continue;
            }
            DeliveryResult build = DeliveryResult.builder()
                    .id(maUserDelivery.getId())
                    .deliveryDay(maUserDelivery.getCreateTime() == null ? null
                            : maUserDelivery.getCreateTime().until(LocalDateTime.now(), ChronoUnit.YEARS))
                    .companyId(companyId)
                    .companyName(maCompany.getCompanyName())
                    .image(maCompany.getLogo())
                    .jobId(maUserDelivery.getJobId())
                    .jobName(maJob.getJobName())
                    .lastLookedDay(maUserDelivery.getLastLookedTime() == null ? null
                            : maUserDelivery.getLastLookedTime().until(LocalDateTime.now(), ChronoUnit.DAYS))
                    .status(maUserDelivery.getStatus())
                    .build();
            deliveryResultList.add(build);
        }
        return deliveryResultList;

    }

    @Override
    public ListPagingResponse<UserBaseMessageResult> queryUserPageByJob(DeliveryQueryCondition condition, Long jobId) {
        Page<MaUserDelivery> page = new Page<>(condition.getPageIndex(), condition.getPageSize());
        MaUserDelivery maUserDelivery = new MaUserDelivery();
        BeanUtils.copyProperties(condition, maUserDelivery);
        QueryWrapper<MaUserDelivery> entityWrapper = new QueryWrapper<>(maUserDelivery);
        entityWrapper.eq(Column.JOB_ID.getColumn(), jobId);
        entityWrapper.orderByDesc(Column.CREATE_TIME.getColumn());
        Page<MaUserDelivery> maUserDeliveryPage = maUserDeliveryMapper.selectPage(page, entityWrapper);
        List<MaUserDelivery> records = maUserDeliveryPage.getRecords();

        if (records == null || records.size() == 0) {
            return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", new ArrayList(), 0L, 0, 0L);
        }

        List<UserBaseMessageResult> list = records.stream().map(MaUserDelivery::getUserId)
                .map(a -> resumeService.getByUserId(a).getResponseData()).collect(Collectors.toList());
        return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", list,
                maUserDeliveryPage.getCurrent(), maUserDeliveryPage.getRecords().size(), maUserDeliveryPage.getTotal());
    }

    @Override
    public ListPagingResponse<UserBaseMessageResult> queryUserPageByCompany(DeliveryQueryCondition condition,
            Long companyId) {
        Page<MaUserDelivery> page = new Page<>(condition.getPageIndex(), condition.getPageSize());
        MaUserDelivery maUserDelivery = new MaUserDelivery();
        BeanUtils.copyProperties(condition, maUserDelivery);
        QueryWrapper<MaUserDelivery> entityWrapper = new QueryWrapper<>(maUserDelivery);
        entityWrapper.eq(Column.COMPANY_ID.getColumn(), companyId);
        entityWrapper.orderByDesc(Column.CREATE_TIME.getColumn());
        Page<MaUserDelivery> maUserDeliveryPage = maUserDeliveryMapper.selectPage(page, entityWrapper);
        List<MaUserDelivery> records = maUserDeliveryPage.getRecords();

        if (records == null || records.size() == 0) {
            return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", new ArrayList(), 0L, 0, 0L);
        }

        List<UserBaseMessageResult> list = records.stream().map(MaUserDelivery::getUserId)
                .map(a -> resumeService.getByUserId(a).getResponseData()).collect(Collectors.toList());
        return new ListPagingResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", list,
                maUserDeliveryPage.getCurrent(), maUserDeliveryPage.getRecords().size(), maUserDeliveryPage.getTotal());
    }

    @Override
    public BaseResponse updateByCompanyId(DeliveryParam deliveryParam, Long userId) {
        MaUserDelivery build = new MaUserDelivery();
        BeanUtils.copyProperties(deliveryParam, build);
        // 根据userId和jobId
        UpdateWrapper<MaUserDelivery> userDeliveryUpdateWrapper = new UpdateWrapper<>();
        userDeliveryUpdateWrapper.eq(Column.USER_ID.getColumn(), userId);
        userDeliveryUpdateWrapper.eq(Column.COMPANY_ID.getColumn(), getCompanyId());
        maUserDeliveryMapper.update(build, userDeliveryUpdateWrapper);
        return new BaseResponse(ResponseCodeEnum.SUCCESS, "插入成功");
    }
}